package com.lucenly.card.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.lucenly.card.R;
import com.lucenly.card.base.BaseActivity;
import com.lucenly.card.bean.PayBean;
import com.lucenly.card.bean.PayResult;
import com.lucenly.card.constants.UrlDefend;
import com.lucenly.card.event.StringMsgEvent;
import com.lucenly.card.view.dialog.MsgDialog;
import com.siberiadante.toastutils.ToastUtil;
import com.vise.xsnow.dialog.PromptDialog;
import com.vise.xsnow.event.BusManager;
import com.vise.xsnow.http.ViseHttp;
import com.vise.xsnow.http.callback.ACallback;
import com.vise.xsnow.utls.SharedPreferencesUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

import butterknife.BindView;
import ezy.ui.layout.LoadingLayout;

public class PayActivity extends BaseActivity {
    @BindView(R.id.ll_back)
    LinearLayout ll_back;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.view)
    LoadingLayout view;
    @BindView(R.id.tv_goods)
            TextView tv_goods;
    @BindView(R.id.tv_payNo)
            TextView tv_payNo;
    @BindView(R.id.tv_goodsName)
            TextView tv_goodsName;
    @BindView(R.id.tv_amount)
            TextView tv_amount;
    String amount;
    @BindView(R.id.ll_zfb)
    LinearLayout ll_zfb;
    @BindView(R.id.ll_ye)
            LinearLayout ll_ye;
    PayBean payBean;
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;
    MsgDialog dialog;
    /** 支付宝支付业务：入参app_id */
//    public static final String APPID = "2018081761056698";

    /** 支付宝账户登录授权业务：入参pid值 */
//    public static final String PID = "2088921725445773";

    /** 商户私钥，pkcs8格式 */
    /** 如下私钥，RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个 */
    /** 如果商户两个都设置了，优先使用 RSA2_PRIVATE */
    /** RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议使用 RSA2_PRIVATE */
    /** 获取 RSA2_PRIVATE，建议使用支付宝提供的公私钥生成工具生成， */
    /** 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1 */
//    public static final String RSA2_PRIVATE = "";
//    public static final String RSA_PRIVATE = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC+YgBmLytmhESNTay5WlNsm/4vIBGTkZggAT8qa/NVeJhuacnBxoZ/Qb9BIAIn0sHioHcRXQk3UE5YEkE+rXCSPqja3DNogIyCm1F/LvHVKBI1J22HcM6aKKeClbyPtpFocZCcvtcaX9EQckhe11jJbg75JtJp9r4LukdfK1ua04o+d0i0vvX2CJP6jpTlQAbvxGJOc7Hm9SJ9MTzb0apKiZmA9PCSZgNG24Ex0fDXc//WrxyeJk6yj/tz6Yn+DskSnMFY+OYPwPAUht0bCAaZnzzJzeBKlzsuFrkdqAoz5g4/b4s91vnIv1iqkyfYZVjSBqGeGgeiE0NuTaVrvcTZAgMBAAECggEALPLUZ0vBsm2OBdKN8iEKSz01MQkgPTgFs6C3uhtMkyRq0L63PMHTZV4ven/FIoPW9Nuv4PCXSXDzXkXJE7Q9PLoAgdO1a3nWMsva3O1HeW0Bh30sleqjTLBGhEU4BLI0+HS/kNJZ1MdEg96HiaTMOJp8fISW7x+rVPeA/E4vTYk1sanE5KMfdsTcsCQM3KedRW3bhkcSy4itgfou/8fqpBBkubZoQ38jR7HZXChFduPYMBRGMvysiGhQeOj6PF1WF6dr5q+LBz4OY4BuEAl3hcMD5IfT014kdAw/u8Df0nLXEb0KdjjRqf3W8//p8bpekZeCXbd1kQUGTjKWIlfY0QKBgQDuK9t0tffFv2HF2bpXpAFq9xrxwDdPQp0Xa9xu8UnPxJkyawHoIvWGS80Kr/BPlIO4ZV9uIq4KKEWriStmgcat7FaQ5q9ehLidlv8Fjspuw3n/OMA2WqcXQvzBCVl8RCFqCwnR3JfzZdJrZAC9RlxRIVHZWXlBc8RFlk9ZMYa+LQKBgQDMolwv4RAmXvuXKnZprtSXJ/H5NvONodq27QDwOx9dgoe+KPlNyxd/ImG3WM5tcKWtNjz28eJULH/ewyjmmCq/bKoYUnbEoW7XQRyJ5QdRAPiwz0iXTe4w4u7jvtvSfldvqjZNkZHAZ4h/+34/uZbMfjnrkj5HAixkBYsbOPD43QKBgDAiYvbic9HeTOdMipF9zt+MU0C6hTMall8OaH1vfGhmJkP/RmJg9lgO58CaMCoVLM3OhwveLGhXHUV+smvEHKA33ILqbFTg4+LNinrYEedy0CwZjxctGQnleumUdyZbKpmg43orZ/ZEBNO5YUDfgHbREhaoM45b1DXwG9c94Cp9AoGAMLm0Q75ObySMuajluzJi8n8Tcejww1e30XjLkWgyhryO/+uXuTtTo/UW2WZu+MYq3PyeNZrQ7oQOCofj1EyFWUFRmyr/lsBtuRmK5xa+0D3v+YHR4h0vSzqt8VK/2vY0caVQ+tVfpDXC3d6PaDMTwiuINRyEcboFwedEAT5kuo0CgYEA7OeSb3wh0jM7wAxIzNLS54MYcjLiOzWz6Ld1Ligi7UhEXVmHhMYr2BRBgEX8xZBsJ8uydb0d5kQPBMRDYo2xZa7OLhZmk5Pwy+/jrUqyjwslCWiJfzLMj1R8e+eES0SZakZnFNhNV1rwkn8ao0eJShT0ma1tVvQDp9tj6LfhVCQ=";
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                        PaySucuessDialog dialog = new PaySucuessDialog(PayActivity.this,"确定");
//                        dialog.show();
                        yz();
                    } else {
                        ll_zfb.setEnabled(true);
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
//                        DialogUtil.showNotDialog(bActivity, true, R.mipmap.pay_sucess_icon, getResources().getColor(R.color.yellow_text), "\n充值失败\n\n");
                        ToastUtil.showSingletonShort("充值失败");
                    }
                    break;
                }
                default:
                    break;
            }
        };
    };

    /**
     * 验证
     */
    private void yz() {
        final PromptDialog dialog = new PromptDialog(PayActivity.this);
        dialog.showLoading("验证中,请稍等...");
        ViseHttp.POST(UrlDefend.YZ_PAY)
                .addHeader("Token", SharedPreferencesUtil.getInstance().getString("Token"))
                .addParam("payNo",payBean.payNo)
                .request(new ACallback<String>() {
                    @Override
                    public void onSuccess(String data) {
                        ll_zfb.setEnabled(true);
                        dialog.dismiss();
                        BusManager.getBus().post(new StringMsgEvent("TIXIAN"));
                        BusManager.getBus().post(new StringMsgEvent("CHONGZHI"));
                        finish();
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        ll_zfb.setEnabled(true);
                        dialog.dismiss();
                        ToastUtil.showSingletonShort(errMsg);
                    }
                });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay);
    }

    @Override
    protected void initView() {
        ll_back.setVisibility(View.VISIBLE);
        tv_title.setText("支付");
        amount = getIntent().getStringExtra("amount");
    }

    @Override
    protected void bindEvent() {
        ll_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        C(ll_zfb);
        C(ll_ye);
    }

    @Override
    protected void initData() {
        getOrder();
    }

    private void getOrder() {
        ViseHttp.POST(UrlDefend.GET_ORDER)
                .addHeader("Token", SharedPreferencesUtil.getInstance().getString("Token"))
                .addParam("amount",amount)
                .request(new ACallback<PayBean>() {
                    @Override
                    public void onSuccess(PayBean data) {
                        payBean = data;
                        tv_goods.setText(data.goods+"");
                        tv_payNo.setText(data.payNo+"");
                        tv_goodsName.setText(data.goodsName+"");
                        tv_amount.setText("¥ "+data.amount+"元");
                        view.showContent();
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
//                        view.setErrorText(errMsg);
//                        view.showError();
                        dialog = new MsgDialog(PayActivity.this,errMsg,false);
                        dialog.show();
                    }
                });
    }

    @Override
    protected void processClick(View view) {
        switch (view.getId()){
            case R.id.ll_zfb:
                ll_zfb.setEnabled(false);
                pay();
                break;
            case R.id.ll_ye:
                ll_ye.setEnabled(false);
                payByYe();
                break;
        }
    }
    public void payByYe(){
        if(payBean==null){
            ll_zfb.setEnabled(true);
            ToastUtil.showSingletonShort("获取订单号失败");
            return;
        }
        final PromptDialog dialog = new PromptDialog(this);
        dialog.showLoading("加载中...");
        ViseHttp.POST(UrlDefend.PAY_YE)
                .addHeader("Token", SharedPreferencesUtil.getInstance().getString("Token"))
                .addParam("payNo",payBean.payNo)
                .request(new ACallback<String>() {
                    @Override
                    public void onSuccess(String data) {
                        dialog.dismiss();
                        ll_ye.setEnabled(true);
                        BusManager.getBus().post(new StringMsgEvent("TIXIAN"));
                        BusManager.getBus().post(new StringMsgEvent("CHONGZHI"));
                        finish();
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        ll_ye.setEnabled(true);
                        ToastUtil.showSingletonShort(""+errMsg);
                        dialog.dismiss();
                    }
                });
    }

    /**
     * 支付宝支付
     */
    private void pay() {
        if(payBean==null){
            ll_zfb.setEnabled(true);
            ToastUtil.showSingletonShort("获取订单号失败");
            return;
        }
//        boolean rsa2 = (RSA2_PRIVATE.length() > 0);
//        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2);
//        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);
//
//        String privateKey = rsa2 ? RSA2_PRIVATE : RSA_PRIVATE;
//        String sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2);
//        final String orderInfo = orderParam + "&" + sign;
        final PromptDialog dialog = new PromptDialog(this);
        dialog.showLoading("加载中...");
        ViseHttp.POST(UrlDefend.PAY_ZFB)
                .addHeader("Token", SharedPreferencesUtil.getInstance().getString("Token"))
                .addParam("way","2")
                .addParam("payNo",payBean.payNo)
                .request(new ACallback<String>() {
                    @Override
                    public void onSuccess(String data) {
//                        ToastUtil.showSingletonShort(data);
                        dialog.dismiss();
                        try {
                            JSONObject jsonObject = new JSONObject(data);
                           final String orderInfo = jsonObject.getString("string");
                            Runnable payRunnable = new Runnable() {
                            @Override
                            public void run() {
                                PayTask alipay = new PayTask(PayActivity.this);
                                Map<String, String> result = alipay.payV2(orderInfo, true);

                                Message msg = new Message();
                                msg.what = SDK_PAY_FLAG;
                                msg.obj = result;
                                mHandler.sendMessage(msg);
                            }
                        };

                        Thread payThread = new Thread(payRunnable);
                        payThread.start();
                        } catch (JSONException e) {
                            ll_zfb.setEnabled(true);
                            e.printStackTrace();
                            }
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        ll_zfb.setEnabled(true);
                        ToastUtil.showSingletonShort(""+errMsg);
                        dialog.dismiss();
                    }
                });
    }
}
